/**
 * 2024/01/01 - 2024/12/31
 **/
package com.snail.camunda.engin.process.holder;

import com.snail.camunda.engin.process.dto.TodoDTO;
import com.snail.starter.commons.page.PageQO;
import com.snail.starter.commons.page.PageVO;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.task.TaskQuery;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author: (zg)
 * @Date: 2024/12/16 11:32
 * @Version: 1.0.0
 */
@Component
public class TaskHolder {

    @Resource
    TaskService taskService;

    public TaskQuery createTaskQuery(TodoDTO todo) {
        TaskQuery taskQuery = taskService.createTaskQuery();
        if (null != todo.getAssignee()) {
            taskQuery.taskAssignee(todo.getAssignee());
        }
        return taskQuery;
    }

    public long count(TaskQuery taskQuery) {
        return taskQuery.count();
    }

    public PageVO<Task> page(PageQO<TodoDTO> page) {
        return page(page, task -> task);
    }

    public <T> PageVO<T> page(PageQO<TodoDTO> page, Function<Task, T> function) {
        TaskQuery taskQuery = createTaskQuery(page.getQuery());
        long count = count(taskQuery);
        if (0L == count) {
            return PageVO.of(page.getPageNum() - 1, page.getPageSize(), 0L, new ArrayList<>());
        }
        List<Task> tasks = taskQuery.listPage(page.getPageNum(), page.getPageSize());
        if (null == tasks || tasks.isEmpty()) {
            return PageVO.of(page.getPageNum(), page.getPageSize(), count, new ArrayList<>());
        }
        return PageVO.of(page.getPageNum(), page.getPageSize(), count, tasks.stream().map(function).collect(Collectors.toList()));
    }

}
